import { Navigate, useLocation } from "react-router-dom";

const AuthGuard = ({ element, requiresAuth, roles }) => {
  const currentUser = JSON.parse(localStorage.getItem("user") || null);
  const location = useLocation();

  if (requiresAuth && !currentUser) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  if (
    requiresAuth &&
    roles &&
    roles.length > 0 &&
    !roles.includes(currentUser?.role)
  ) {
    return <Navigate to="/" replace />;
  }

  return element;
};

export default AuthGuard;
